package cn.sanli.manage.controller;

import cn.sanli.manage.ex.ServiceException;
import cn.sanli.manage.pojo.dto.Fault.FaultInsertRequest;
import cn.sanli.manage.pojo.dto.Fault.FaultUpdateRequest;
import cn.sanli.manage.pojo.dto.Fault.PageQueryOfFaultRequest;
import cn.sanli.manage.pojo.entity.Fault;
import cn.sanli.manage.pojo.vo.Fault.FaultPagingQueryVO;
import cn.sanli.manage.pojo.vo.Fault.FaultStatisticsInfoOfDeptVO;
import cn.sanli.manage.pojo.vo.Fault.FaultStatisticsInfoVO;
import cn.sanli.manage.pojo.vo.Fault.FaultStatisticsVO;
import cn.sanli.manage.security.LoginPrincipal;
import cn.sanli.manage.service.FaultService;
import cn.sanli.manage.utils.DateUtils;
import cn.sanli.manage.utils.StringUtils;
import cn.sanli.manage.web.JsonResult;
import cn.sanli.manage.web.ServiceCode;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 过错信息表(Fault)表控制层
 *
 * @author wzy
 * @since 2023-12-07 16:58:13
 */
@RestController
@RequestMapping("/fault")
@Slf4j
@Api(tags = "过错信息管理接口")
public class FaultController {
    /**
     * 服务对象
     */
    @Resource
    private FaultService faultService;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryOne")
    @ApiOperation("通过主键查询单条数据")
    public JsonResult<Fault> queryById(Integer id) {
        log.debug("开始查询id为{}的过错信息表中的数据.................................................", id);
        if(id == null) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "请求不能为空");
        }
        Fault fault = faultService.queryById(id);
        return JsonResult.ok(fault);
    }

    /**
     * 新增数据
     *
     * @param faultInsertRequest 实体
     * @return 新增结果
     */
    @PostMapping("/insert")
    @ApiOperation("新增一条数据")
    public JsonResult<?> add(@RequestBody FaultInsertRequest faultInsertRequest, @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理新增过错信息请求, 参数: {}, 当事人: {}.................................................", faultInsertRequest.toString(), loginPrincipal.toString());
        if(StringUtils.isAnyBlank(faultInsertRequest.getResName(), faultInsertRequest.getFaultContent(), faultInsertRequest.getDisposalDept(),
                faultInsertRequest.getDisposalName(), faultInsertRequest.getDisposalNum()))
        {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数不完整");
        }
        boolean whether = faultService.insert(faultInsertRequest, loginPrincipal);
        if(!whether) {
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, "新增数据失败");
        }
        return JsonResult.ok();
    }


    /**
     * 修改数据
     *
     * @param faultUpdateRequest 实体
     * @return 新增结果
     */
    @PostMapping("/update")
    @ApiOperation("修改一条数据")
    public JsonResult<?> update(@RequestBody FaultUpdateRequest faultUpdateRequest, @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理修改过错信息请求, 参数: {}.................................................", faultUpdateRequest.toString());
        if(StringUtils.isAnyBlank(faultUpdateRequest.getResName(), faultUpdateRequest.getFaultContent(), faultUpdateRequest.getDisposalDept(),
                faultUpdateRequest.getDisposalName()) || faultUpdateRequest.getDisposalDetails() == null)
        {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数不完整");
        }
        boolean whether = faultService.update(faultUpdateRequest, loginPrincipal);
        if(!whether) {
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, "修改数据失败");
        }
        return JsonResult.ok();
    }


    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/deleteOne")
    @ApiOperation("根据id删除一条数据")
    public JsonResult<?> deleteById(@ApiParam(name = "id", value = "过错id", required = true)
                                        @RequestParam Integer id) {
        log.debug("开始删除id为{}的过错信息表数据.................................................", id);
        if(id == null) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数不完整");
        }
        boolean whether = faultService.deleteById(id);
        if(!whether) {
            throw new ServiceException(ServiceCode.ERROR_DELETE, "根据id删除数据失败");
        }
        return JsonResult.ok();
    }

    /**
     * 根据多条件分页查询过错信息
     *
     * @param queryRequest 查询条件封装类
     * @return 符合条件的过错信息集合
     */
    @PostMapping("/pagingQuery")
    @ApiOperation("根据多条件分页查询过错信息")
    public JsonResult<PageInfo<FaultPagingQueryVO>> pagingQuery(@RequestBody PageQueryOfFaultRequest queryRequest) {
        // 判断时间是否准确, 如果开始时间大于现在时间, 以上方法结果不小于0
        if (queryRequest.getStartTime() != null &&
                queryRequest.getStartTime().getTime() > DateUtils.getNowDate().getTime()) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "起始时间不能大于当前时间");
        }
        PageHelper.startPage(queryRequest.getPageNum(), queryRequest.getPageSize());

        List<FaultPagingQueryVO> faultAndFaultAssessInfos = faultService.pagingQuery(queryRequest);

        PageInfo<FaultPagingQueryVO> pageInfo = new PageInfo<>(faultAndFaultAssessInfos);

        return JsonResult.ok(pageInfo);
    }



    /**
     * 奖惩信息导出到excel表格
     *
     * @param queryRequest 查询条件
     * @param response 响应
     */
    @PostMapping ("/dataEduce")
    @ApiOperation("数据导出excel")
    public void dataEduce(@RequestBody PageQueryOfFaultRequest queryRequest, HttpServletResponse response)  {
        log.debug("开始处理将数据导出到excel的请求, 请求参数: {}", queryRequest.toString());
        // 先将需要的数据查询出来
        PageHelper.startPage(queryRequest.getPageNum(), queryRequest.getPageSize());
        List<FaultPagingQueryVO> faultAndFaultAssessInfos = faultService.pagingQuery(queryRequest);
        PageInfo<FaultPagingQueryVO> pageInfo = new PageInfo<>(faultAndFaultAssessInfos);
        log.debug("获取到的过错信息数据: {}", pageInfo.getList());

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String finalFileName = URLEncoder.encode("考核信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + finalFileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), FaultPagingQueryVO.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("")
                    .doWrite(pageInfo.getList());
        } catch (IOException e){
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "Excel表格导出过程中出现IOException");
        }
    }


    /**
     * 个人考核统计
     *
     * @param loginPrincipal 当事人
     */
    @GetMapping ("/statisticsOfPersonage")
    @ApiOperation("个人考核统计")
    public JsonResult<List<FaultStatisticsInfoVO>> statisticsOfPersonage(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal)  {
        log.debug("开始执行个人考核积分统计, 当事人: {}", loginPrincipal);
        List<FaultStatisticsInfoVO> statisticsInfoVOList = faultService.statisticsFaultOfPersonage(loginPrincipal);
        return JsonResult.ok(statisticsInfoVOList);
    }


    /**
     * 部门考核统计
     *
     * @param loginPrincipal 当事人
     */
    @GetMapping ("/statisticsOfDept")
    @ApiOperation("部门考核统计")
    public JsonResult<List<FaultStatisticsInfoOfDeptVO>> statisticsOfDept(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal)  {
        log.debug("开始执行个人考核积分统计, 当事人: {}", loginPrincipal);
        List<FaultStatisticsInfoOfDeptVO> statisticsInfoVOList = faultService.statisticsFaultOfDept(loginPrincipal);
        return JsonResult.ok(statisticsInfoVOList);
    }


    /**
     * 大口考核统计
     *
     * @param loginPrincipal 当事人
     */
    @GetMapping ("/statisticsOfCenter")
    @ApiOperation("大口考核统计")
    public JsonResult<List<FaultStatisticsInfoOfDeptVO>> statisticsOfCenter(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal)  {
        log.debug("开始执行个人考核积分统计, 当事人: {}", loginPrincipal);
        List<FaultStatisticsInfoOfDeptVO> statisticsInfoVOList = faultService.statisticsFaultOfDept(loginPrincipal);
        return JsonResult.ok(statisticsInfoVOList);
    }




}

